package server;

import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLClassLoader;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.Executors;
import java.util.concurrent.RejectedExecutionHandler;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

/**
 * Minicat的主类
 */
public class Bootstrap {

    private List<Service> services;


    /**
     * Minicat启动需要初始化展开的一些操作
     */
    public void start() throws Exception {
        // 加载解析相关的配置，server.xml
        loadConfig();


        for (Service service : services) {
            Host host = service.getHost();
            // 加载解析servce下的项目配置文件web.xml
            loadServlet(new File( host.getAppBase()), 0, null, host);
        }



        // 定义一个线程池
        // 核心线程数
        int corePoolSize = 10;
        // 最大线程数
        int maximumPoolSize = 50;
        // 存活时间
        long keepAliveTime = 100L;
        // 时间单位
        TimeUnit unit = TimeUnit.SECONDS;
        // 储存方式
        BlockingQueue<Runnable> workQueue = new ArrayBlockingQueue<>(50);
        // 工厂
        ThreadFactory threadFactory = Executors.defaultThreadFactory();
        // 拒绝策略
        RejectedExecutionHandler handler = new ThreadPoolExecutor.AbortPolicy();


        ThreadPoolExecutor threadPoolExecutor = new ThreadPoolExecutor(
                corePoolSize,
                maximumPoolSize,
                keepAliveTime,
                unit,
                workQueue,
                threadFactory,
                handler
        );

        for (Service service : services) {
            service.setThreadPoolExecutor(threadPoolExecutor);
            service.start();
        }



    }

    private static final String CONFIG_PATH = "/server.xml";
    private void loadConfig(){
        InputStream resourceAsStream = null;

        resourceAsStream = this.getClass().getResourceAsStream(CONFIG_PATH);

        SAXReader saxReader = new SAXReader();
        Document document = null;
        try {
            document = saxReader.read(resourceAsStream);
            Element rootElement = document.getRootElement();
            List<Element> list = rootElement.selectNodes("//service");
            services = new ArrayList<>();
            for (Element element : list) {
                Element connector = (Element)element.selectSingleNode("//connector");
                String port = connector.attributeValue("port");
                Service service = new Service();
                service.setPort(Integer.valueOf(port));
                Host host = new Host();
                service.setHost(host);
                Element hostNode = (Element)rootElement.selectSingleNode("//Host");
                String name = hostNode.attributeValue("name");
                String appBase = hostNode.attributeValue("appBase");
                host.setName(name);
                host.setAppBase(appBase);
                services.add(service);
            }
        } catch (DocumentException e) {
            e.printStackTrace();
        }
    }


    /**
     * 加载解析web.xml，初始化Servlet
     *
     * @param dir
     * @param context
     */
    private void doLoadServlet(File dir, Context context, Host host) {
        InputStream resourceAsStream = null;
        try {
            resourceAsStream = new FileInputStream(dir);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
        SAXReader saxReader = new SAXReader();

        try {
            Document document = saxReader.read(resourceAsStream);
            Element rootElement = document.getRootElement();

            List<Element> selectNodes = rootElement.selectNodes("//servlet");

            // 创建项目的classloard
            URL url = new URL("file:" + host.getAppBase() + "/" + context.getName() + "/");

            // TODO URLClassLoader如果本项目中已经有同名类，根据java双亲委派的特性，这里会加载Minicat中的类，不会去加载项目中的servlet
            // 所以最好好是自定义类加载器，防止这种情况的出现！！
            ClassLoader loader = new URLClassLoader(new URL[]{url});

            for (int i = 0; i < selectNodes.size(); i++) {
                Element element = selectNodes.get(i);
                // <servlet-name>lagou</servlet-name>
                Element servletnameElement = (Element) element.selectSingleNode("servlet-name");
                String servletName = servletnameElement.getStringValue();
                // <servlet-class>server.LagouServlet</servlet-class>
                Element servletclassElement = (Element) element.selectSingleNode("servlet-class");
                String servletClass = servletclassElement.getStringValue();
                // 根据servlet-name的值找到url-pattern
                Element servletMapping = (Element) rootElement.selectSingleNode("/web-app/servlet-mapping[servlet-name='" + servletName + "']");
                // /lagou
                String urlPattern = servletMapping.selectSingleNode("url-pattern").getStringValue();

                Class<?> clazz = loader.loadClass(servletClass);//自己定义的loader路径可以找到
                HttpServlet httpServlet = (HttpServlet)clazz.newInstance();
                Wrapper wrapper = new Wrapper();
                wrapper.setPath(urlPattern);
                wrapper.setServlet(httpServlet);
                context.getWapperMap().put(urlPattern, wrapper);
            }
        } catch (DocumentException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InstantiationException e) {
            e.printStackTrace();
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (MalformedURLException e) {
            e.printStackTrace();
        }
    }

    public void loadServlet(File dir, int index, Context context, Host host) {
        index++;
        if (dir.isDirectory()) {
            String[] children = dir.list();
            for (int i = 0; i < children.length; i++) {
                // 保存根项目名
                if (index == 1) {
                    context = new Context();
                    context.setName(children[i]);
                    host.getContextList().add(context);
                }
                loadServlet(new File(dir, children[i]), index, context, host);
            }
        } else {
            if (index == 1) {
                throw new RuntimeException("部署目录不能是文件路径");
            }
            String name = dir.getName();
            if ("web.xml".equals(name)) {
                doLoadServlet(dir, context, host);
            }
        }
    }

    /**
     * Minicat 的程序启动入口
     *
     * @param args
     */
    public static void main(String[] args) {
        Bootstrap bootstrap = new Bootstrap();
        try {
            // 启动Minicat
            bootstrap.start();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
